package com.waves.search.service.user;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waves.core.utils.StringUtils;
import com.waves.core.web.domain.TableDataInfo;
import com.waves.search.dto.EsSearchDTO;
import com.waves.search.vo.user.UserEsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eden
 * @date 2024/10/14 21:17
 **/
@Slf4j
@RequiredArgsConstructor
@Component
public class UserSearchServiceImpl implements UserSearchService {

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public TableDataInfo<UserEsVO> pageTask(EsSearchDTO esSearchDTO) {
        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(esSearchDTO.getKeyword())) {
            criteria = Criteria.where(UserEsVO.Fields.name).matches(esSearchDTO.getKeyword());
        }

        SearchHits<UserEsVO> search = elasticsearchRestTemplate.search(CriteriaQuery.builder(criteria)
                        .withPageable(esSearchDTO)
                        .build(),
                UserEsVO.class);
        SearchPage<UserEsVO> searchPage = SearchHitSupport.searchPageFor(search, esSearchDTO);
        Page<UserEsVO> page = new Page<>();
        List<UserEsVO> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(searchPage.getContent())) {
            for (SearchHit<UserEsVO> userEsVOSearchHit : searchPage.getContent()) {
                list.add(userEsVOSearchHit.getContent());
            }
        }

        page.setRecords(list).setCurrent(esSearchDTO.getPageNumber())
                .setSize(esSearchDTO.getPageSize()).setTotal(searchPage.getTotalElements());
        return TableDataInfo.build(page);
    }
}
